<script>
import { request } from '@/util/request.js'
import { refreshTabBar } from '@/util/tabbar.js'
import Loader from '@/components/Loader/Loader.vue'
import MyTabbar from '@/components/MyTabbar/MyTabbar.vue'
export default {
	components: { Loader, MyTabbar },
	data() {
		return {
			loading: true,
			completionStatus: {
				screening: false,
				assessment: false,
				healthTest: false
			},
			completionDates: {
				screening: '',
				assessment: '',
				healthTest: ''
			}
		};
	},
	computed: {
		// 筛查描述文本
		screeningDesc() {
			return this.completionStatus.screening ? '查看筛查报告' : '内在能力筛查评估';
		},
		// 完成进度（与 assess_list 一致的进度条展示逻辑）
		progressPercent() {
			const total = 3;
			const done = (this.completionStatus.screening ? 1 : 0)
				+ (this.completionStatus.assessment ? 1 : 0)
				+ (this.completionStatus.healthTest ? 1 : 0);
			return Math.round((done / total) * 100);
		}
	},
	methods: {
		getAssessQuesNames() {
			return ['a1_cognition', 'a2_movement', 'a3_nutrition', 'a4_vision', 'a5_hearing', 'a6_emotion'];
		},
		getHealthtestQuesNames() {
			return ['h1_important_effect', 'h2_dangerous_effect'];
		},

		// 从后端获取完成状态（无缓存，每次获取）
		async fetchSurveyStatus() {
			try {
				const res = await request({ url: '/survey/status/' });
				if (res && res.statusCode === 200 && res.data) {
					this.applySurveyStatus(res.data);
				}
			} catch (e) {
				console.error('fetch survey status failed:', e);
			}
		},

		// 将后端状态映射到本地UI与旧有本地键值
		applySurveyStatus(statusData) {
			// statusData: { screening: ISO|null, assessment: ISO|null, healthtest: ISO|null }
			const status = {
				screening: !!statusData.screening,
				assessment: !!statusData.assessment,
				healthTest: !!statusData.healthtest,
			};
			const dates = {
				screening: statusData.screening ? new Date(statusData.screening).getTime() : '-',
				assessment: statusData.assessment ? new Date(statusData.assessment).getTime() : '-',
				healthTest: statusData.healthtest ? new Date(statusData.healthtest).getTime() : '-',
			};
			this.$storage.set('test_completion_status', status);
			this.$storage.set('test_completion_dates', dates);
			this.completionStatus = status;
			this.completionDates = {
				screening: this.formatDate(dates.screening),
				assessment: this.formatDate(dates.assessment),
				healthTest: this.formatDate(dates.healthTest),
			};
		},
		// 处理IC筛查点击
		handleScreeningClick() {
			if (this.completionStatus.screening) {
				// 有结果时，跳转到查看报告
				uni.navigateTo({
					url: '/sub_pages/pages/screening_result/screening_result'
				});
			} else {
				// 无结果时，跳转到问卷
				uni.navigateTo({
					url: '/sub_pages/pages/screening_explain/screening_explain'
				});
			}
		},

		// 显示重新测试确认
		showRetestConfirm(kind) {
			uni.showModal({
				title: '确认重新测试',
				content: '重新测试将清除当前结果，确定要继续吗？',
				success: (res) => {
					if (res.confirm) {
						this.clearSurveyResult(kind);
					}
				}
			});
		},

		// 清除 a1-a6 问卷记录
		clearAssessmentRecords() {
			const assessmentNames = this.getAssessQuesNames();
			assessmentNames.forEach(quesName => {
				this.$storage.remove(`ans_${quesName}`);
			});
		},

		// 清除健康评估问卷记录
		clearHealthtestRecords() {
			const healthtestNames = this.getHealthtestQuesNames();
			healthtestNames.forEach(quesName => {
				this.$storage.remove(`ans_${quesName}`);
			});
		},

		// 清除对应类型结果并重新测试
		clearSurveyResult(surveyName) {
			let onResultClear;
			if (surveyName === 'screening') {
				onResultClear = () => {
					this.$storage.remove('assess_results');
					this.$storage.remove('assess_details');
					this.clearAssessmentRecords();
					this.completionStatus.screening = false;
					this.completionDates.screening = '';
					this.completionStatus.assessment = false;
					this.completionDates.assessment = '';
					this.$storage.set('test_completion_status', this.completionStatus);
					this.$storage.set('test_completion_dates', this.completionDates);
					uni.navigateTo({ url: '/sub_pages/pages/screening_explain/screening_explain' });
				}
			} else if (surveyName === 'assessment') {
				onResultClear = () => {
					this.$storage.remove('assess_results');
					this.$storage.remove('assess_details');
					this.clearAssessmentRecords();
					this.completionStatus.assessment = false;
					this.completionDates.assessment = '';
					this.$storage.set('test_completion_status', this.completionStatus);
					this.$storage.set('test_completion_dates', this.completionDates);
					uni.navigateTo({ url: '/sub_pages/pages/assess_list/assess_list' });
				}
			} else if (surveyName === 'healthTest') {
				onResultClear = () => {
					this.$storage.remove('healthtest_results');
					this.$storage.remove('healthtest_details');
					this.clearHealthtestRecords();
					this.completionStatus.healthTest = false;
					this.completionDates.healthTest = '';
					this.$storage.set('test_completion_status', this.completionStatus);
					this.$storage.set('test_completion_dates', this.completionDates);
					uni.navigateTo({ url: '/sub_pages/pages/health_test/health_test' });
				}
			}
			else {
				console.error("Unknown survey name: ", surveyName);
				return;
			}
			this.$request({
				url: '/survey/delete/',
				method: 'POST',
				data: { type: surveyName },
				success: () => {
					onResultClear();
				},
				fail: (err) => {
					uni.showToast({
						title: '发生错误',
						icon: 'none'
					});
					console.error("清除问卷失败: ", err);
				},
			})
		},
		onRetest(surveyName) {
			this.showRetestConfirm(surveyName);
		},

		// 处理IC评估点击
		handleAssessmentClick() {
			if (this.completionStatus.assessment) {
				// 已有评估结果，查看报告
				uni.navigateTo({ url: '/sub_pages/pages/assess_result/assess_result' });
				return;
			}
			// 未完成评估，先检查是否已完成筛查
			if (!this.completionStatus.screening) {
				uni.showToast({
					title: '请先完成IC筛查',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			// 跳转到评估列表
			uni.navigateTo({ url: '/sub_pages/pages/assess_list/assess_list' });
		},

		// 跳转到健康评估
		navigateToHealthTest() {
			if (this.completionStatus.healthTest) {
				uni.showToast({
					title: '健康信息评估已完成',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			uni.navigateTo({
				url: '/sub_pages/pages/health_test/health_test'
			});
		},

		// 加载完成状态（优先使用服务端缓存）
		loadCompletionStatus() {
			const status = this.$storage.get('test_completion_status') || {};
			const dates = this.$storage.get('test_completion_dates') || {};
			this.completionStatus = {
				screening: status.screening || false,
				assessment: status.assessment || false,
				healthTest: status.healthTest || false
			};
			this.completionDates = {
				screening: this.formatDate(dates.screening),
				assessment: this.formatDate(dates.assessment),
				healthTest: this.formatDate(dates.healthTest)
			};
		},

		// 格式化日期
		formatDate(date) {
			if (!date) return '';
			const d = new Date(date);
			const yyyy = d.getFullYear();
			const mm = String(d.getMonth() + 1).padStart(2, '0');
			const dd = String(d.getDate()).padStart(2, '0');
			return `${yyyy}-${mm}-${dd}`;
		},
	},

	onShow() {
		// 页面显示时直接从后端获取并同步UI
		this.loading = true;

		refreshTabBar();

		this.fetchSurveyStatus()
			.then(() => {
				this.loadCompletionStatus();
			})
			.catch(() => {
				this.loadCompletionStatus();
			})
			.finally(() => {
				this.loading = false;
			});
	},


};
</script>


<template>
	<view class="flex-col justify-start page">
		<view class="flex-col group_1 title-center">
			<text class="title">健康测评</text>
			<text class="subtitle">通过科学的测评了解您的健康状况</text>
		</view>

		<Loader :loading="loading" class="mt-8">
			<view class="progress-container">
				<progress show-info font-size="12" class="mt-12" :percent="progressPercent" activeColor="#F26A77"
					backgroundColor="#FFFFFF" border-radius="8" active active-mode="forwards" duration="20" />
			</view>
			<view class="flex-col list mt-6">
				<!-- IC筛查 -->
				<view class="test-item" @click="handleScreeningClick">
					<image class="test-icon" src="/static/icon/star.svg"></image>
					<view class="test-content">
						<text class="test-title">IC筛查</text>
						<text class="test-desc">{{ screeningDesc }}</text>
						<view class="content-row" v-if="completionStatus.screening">
							<text class="completion-date">完成时间：{{ completionDates.screening }}</text>
							<image class="retest-icon" src="/static/icon/pen.svg" @click.stop="onRetest('screening')">
							</image>
						</view>
					</view>
					<view class="test-status">
						<image v-if="completionStatus.screening" class="completion-icon"
							src="/static/icon/tick_pink.svg"></image>
						<image v-else class="right-icon" src="/static/icon/towards.svg"></image>
					</view>

				</view>

				<!-- IC评估 -->
				<view class="test-item" @click="handleAssessmentClick">
					<image class="test-icon" src="/static/icon/star.svg"></image>
					<view class="test-content">
						<text class="test-title">IC评估</text>
						<text class="test-desc">内在能力详细评估</text>
						<view class="content-row" v-if="completionStatus.assessment">
							<text class="completion-date">完成时间：{{ completionDates.assessment }}</text>
							<image class="retest-icon" src="/static/icon/pen.svg" @click.stop="onRetest('assessment')">
							</image>
						</view>
					</view>
					<view class="test-status">
						<image v-if="completionStatus.assessment" class="completion-icon"
							src="/static/icon/tick_pink.svg"></image>
						<image v-else-if="completionStatus.screening" class="right-icon" src="/static/icon/towards.svg">
						</image>
						<text v-else class="right-tip">需要先完成IC筛查</text>
					</view>

				</view>

				<!-- 健康评估 -->
				<view class="test-item" @click="navigateToHealthTest">
					<image class="test-icon" src="/static/icon/star.svg"></image>
					<view class="test-content">
						<text class="test-title">健康信息评估</text>
						<text class="test-desc">全面的健康信息评估</text>
						<view class="content-row" v-if="completionStatus.healthTest">
							<text class="completion-date">完成时间：{{ completionDates.healthTest }}</text>
							<image class="retest-icon" src="/static/icon/pen.svg" @click.stop="onRetest('healthTest')">
							</image>
						</view>
					</view>
					<view class="test-status">
						<image v-if="completionStatus.healthTest" class="completion-icon"
							src="/static/icon/tick_pink.svg"></image>
						<image v-else class="right-icon" src="/static/icon/towards.svg"></image>
					</view>

				</view>
			</view>
		</Loader>
		<my-tabbar />
	</view>
</template>

<style scoped lang="css">
.page {
	height: 100vh;
	width: 100%;
	padding-bottom: 150rpx;
	overflow: hidden;
}

/* Loader 由组件内样式提供 */

.group_1 {
	padding-top: 34rpx;
}

.title-center {
	align-items: center;
	text-align: center;
}

.section {
	margin: 0 36rpx 40rpx 36rpx;
	text-align: center;
}

.title {
	display: block;
	font-size: 48rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 16rpx;
}

.subtitle {
	display: block;
	font-size: 28rpx;
	color: #666666;
}

.list {
	padding: 0 36rpx;
}

.progress-container {
	padding: 0 36rpx;
}

.test-item {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	padding: 32rpx 24rpx;
	background-color: #ffffff;
	border-radius: 24rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.test-icon {
	width: 48rpx;
	height: 48rpx;
	margin-right: 24rpx;
}

.test-content {
	flex: 1;
}

.content-row {
	display: flex;
	align-items: center;
	gap: 12rpx;
	margin-top: 8rpx;
}

.test-title {
	display: block;
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	margin-bottom: 8rpx;
}

.test-desc {
	display: block;
	font-size: 26rpx;
	color: #666666;
}

.test-status {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-left: 16rpx;
}

.completion-icon {
	width: 32rpx;
	height: 32rpx;
	margin-bottom: 4rpx;
}

.completion-date {
	font-size: 20rpx;
	color: #F26A77;
}

.test-arrow {
	font-size: 32rpx;
	color: #cccccc;
}

.right-icon {
	width: 48rpx;
	height: 48rpx;
}

.right-tip {
	font-size: 24rpx;
	color: #999999;
}

.retest-container {
	margin: -12rpx 0 24rpx 0;
	padding: 0 24rpx;
}

.retest-button {
	width: 100%;
	height: 60rpx;
	background-color: #f8f8f8;
	border: 2rpx solid #e0e0e0;
	border-radius: 12rpx;
	font-size: 24rpx;
	color: #666666;
	display: flex;
	align-items: center;
	justify-content: center;
}

.retest-button:active {
	background-color: #eeeeee;
}

/* 废弃 card-footer，改为 content-row 内联展示 */

.retest-icon {
	width: 28rpx;
	height: 28rpx;
	opacity: 0.8;
}

.retest-icon:active {
	opacity: 1;
}
</style>


<style>
page {
	background-color: #f5f5f5;
}
</style>
